<?php
namespace app\api\controller;
use app\api\controller\BaseController;
use app\common\errcode\ApiErrCode;
use app\common\errcode\ApiErrMsg;
use think\Loader;

class ChatController extends BaseController
{
    protected $chatModel;

    public function __construct()
    {
        parent::__construct();
        $this->chatModel = new \app\api\model\ChatModel();
    }

    /**
     * 会话
     * @param string $text
     * @param string $chatid
     */
    public function create()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->get();
                $text = file_get_contents('php://input');
                if(empty($text)) return $this->jsonJump(ApiErrCode::PARAM_ERROR,ApiErrMsg::PARAM_ERROR);
                $chatid = !empty($data['chatid']) ? $data['chatid'] : '';
                if(empty($chatid)){
                    //第一次提问,获取标题
                    $chatid = $this->userid . '_' . time() . '_' . rand(100,999);
                    //请求获取title的接口
                    $url = "https://jx-gpt-chat-gpt-koeuqttabl.us-west-1.fcapp.run/chat/{$this->userid}/{$chatid}/title";
                    $res = httpRequest($url,$text);
                    // var_dump($res);
                    if(isset($res['code']) && $res['code'] == 1){
                        $title = isset($res['data']['title']) ? $res['data']['title'] : substr($text, 0, 10);
                        //写入标题
                        $this->chatModel->insert_title($this->userid,$chatid,$title);
                        //再次获取历史聊天,此时历史只保存了第一次的问答
                        $hisurl = "https://jx-gpt-chat-gpt-koeuqttabl.us-west-1.fcapp.run/chat/{$this->userid}/{$chatid}/history";
                        $history = httpRequest($hisurl,$text);
                        if(isset($history['code']) && $history['code'] == 1){
                            return $this->jsonJump(ApiErrCode::SUCCESS,ApiErrMsg::SUCCESS,['answer' => $history['data']['content']]);
                        }
                        \app\common\model\CommonModel::recordLog($this->userid,'abnormal',date('Y-m-d H:i:s'),'warning',isset($history['data']['sub_msg']) ? $history['data']['sub_msg'] : '请求OpenAI接口失败'); 
                    }
                    \app\common\model\CommonModel::recordLog($this->userid,'abnormal',date('Y-m-d H:i:s'),'warning',isset($res['data']['content']) ? $res['data']['content'] : '请求OpenAI接口失败');
                    return $this->jsonJump(ApiErrCode::CHAT_AI_FAIL,ApiErrMsg::CHAT_AI_FAIL . ',' . isset($res['data']['content']) ? $res['data']['content'] : '请求OpenAI接口失败');
                }else{
                    //再次提问,存在chatid
                    $hisurl = "https://jx-gpt-chat-gpt-koeuqttabl.us-west-1.fcapp.run/chat/{$this->userid}/{$chatid}/history";
                    $history = httpRequest($hisurl,$text);
                    if(isset($history['code']) && $history['code'] == 1){
                        return $this->jsonJump(ApiErrCode::SUCCESS,ApiErrMsg::SUCCESS,['answer' => $history['data']['content']]);
                    }
                    \app\common\model\CommonModel::recordLog($this->userid,'abnormal',date('Y-m-d H:i:s'),'warning',isset($history['data']['content']) ? $history['data']['content'] : '请求OpenAI接口失败');
                    return $this->jsonJump(ApiErrCode::CHAT_AI_FAIL,ApiErrMsg::CHAT_AI_FAIL . ',' . isset($history['data']['content']) ? $history['data']['content'] : '请求OpenAI接口失败');
                }  
            }
        } catch (\Exception $e) {
            \app\common\model\CommonModel::recordLog($this->userid,'abnormal',date('Y-m-d H:i:s'),'warning',$e->getMessage());
            return $this->jsonJump(ApiErrCode::SYSTEM_ERROR,ApiErrMsg::SYSTEM_ERROR . ',错误信息:'. $e->getMessage());
        }   
    }

    /**
     * 会话列表
     */
    public function index()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                return $this->jsonJump(ApiErrCode::SUCCESS,ApiErrMsg::SUCCESS,$this->chatModel->list($this->userid));
            }            
        } catch (\Exception $e) {
            \app\common\model\CommonModel::recordLog($this->userid,'abnormal',date('Y-m-d H:i:s'),'warning',$e->getMessage());
            return $this->jsonJump(ApiErrCode::SYSTEM_ERROR,ApiErrMsg::SYSTEM_ERROR . ',错误信息:'. $e->getMessage());
        }
    }

    /**
     * 删除会话
     * @param string    $chatid
     */
    public function delete()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                $validate = Loader::validate('Chat');
                $check = $validate->scene('delete')->check($data);
                if(!$check){
                    return $this->jsonJump(ApiErrCode::PARAM_ERROR,ApiErrMsg::PARAM_ERROR.','.$validate->getError());  
                }
                if($this->chatModel->del($this->userid,$data['chatid']) !== false){
                    return $this->jsonJump(ApiErrCode::SUCCESS,ApiErrMsg::SUCCESS);    
                }
                return $this->jsonJump(ApiErrCode::DELETE_CHAT_FAIL,ApiErrMsg::DELETE_CHAT_FAIL);    
            }        
        } catch (\Exception $e) {
            \app\common\model\CommonModel::recordLog($this->userid,'abnormal',date('Y-m-d H:i:s'),'warning',$e->getMessage());
            return $this->jsonJump(ApiErrCode::SYSTEM_ERROR,ApiErrMsg::SYSTEM_ERROR . ',错误信息:'. $e->getMessage());
        }
    }

    /**
     * 修改会话标题
     * @param string    $chatid
     * @param string    $title
     */
    public function edit()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                $validate = Loader::validate('Chat');
                $check = $validate->scene('edit')->check($data);
                if(!$check){
                    return $this->jsonJump(ApiErrCode::PARAM_ERROR,ApiErrMsg::PARAM_ERROR.','.$validate->getError());  
                }
                if($this->chatModel->edit($this->userid,$data) !== false){
                    return $this->jsonJump(ApiErrCode::SUCCESS,ApiErrMsg::SUCCESS);    
                }
                return $this->jsonJump(ApiErrCode::EDIT_TITLE_FAIL,ApiErrMsg::EDIT_TITLE_FAIL);
            }        
        } catch (\Exception $e) {
            \app\common\model\CommonModel::recordLog($this->userid,'abnormal',date('Y-m-d H:i:s'),'warning',$e->getMessage());
            return $this->jsonJump(ApiErrCode::SYSTEM_ERROR,ApiErrMsg::SYSTEM_ERROR . ',错误信息:'. $e->getMessage());
        }
    }

    /**
     * 会话详情
     */
    public function info()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                if(empty($data['chatid'])){
                    return $this->jsonJump(9000,'缺少参数');    
                }
                return $this->jsonJump(ApiErrCode::SUCCESS,ApiErrMsg::SUCCESS,$this->chatModel->info($data['chatid'],$data));    
            }        
        } catch (\Exception $e) {
            \app\common\model\CommonModel::recordLog($this->userid,'abnormal',date('Y-m-d H:i:s'),'warning',$e->getMessage());
            return $this->jsonJump(ApiErrCode::SYSTEM_ERROR,ApiErrMsg::SYSTEM_ERROR . ',错误信息:'. $e->getMessage());
        }    
    }
}